# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: 抢票运用进程.py
Author: kij
Create Date: 2021/3/18
-------------------------------------------------
"""
from multiprocessing import Process, Lock
import time
import json


def show_tick(name):
	time.sleep(1)
	# load 方法读取json文件
	dic = json.load(open('ticket.txt', 'r', encoding='utf-8'))
	print('%s查看剩余票数为%s' % (name, dic['count']))


def buy_tick(name):
	time.sleep(1)
	dic = json.load(open('ticket.txt', 'r', encoding='utf-8'))
	if dic['count'] > 0:
		dic['count'] -= 1
		time.sleep(3)
		json.dump(dic, open('ticket.txt', 'w', encoding='utf-8'))
		print('%s购票成功' % (name,))
	pass


def tesk(name, lock):
	# 进程方法
	show_tick(name)
	# 拿到锁 保证买票的时候只能有一个
	lock.acquire()
	buy_tick(name)
	lock.release()


if __name__ == '__main__':
	lock = Lock()
	start = time.time()
	process = []
	for item in range(10):
		p = Process(target=tesk, args=("路人%s" % item, lock))
		process.append(p)
		p.start()
		# 这样相当于串联了所有的子进程在主进程上面
		# p.join()
	# 这样相当于并联在主线程上一起进行
	for item in process:
		item.join()
	stop = time.time()
	print(stop - start)
